package com.security.brows.room

import android.content.Context
import android.graphics.Bitmap
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

@Entity(tableName = "web_favorite")
class BrowsWebFavoriteBean {
    @PrimaryKey
    @ColumnInfo("url")
    var webUrl: String = ""

    @ColumnInfo("time")
    var time: Long = 0L

    @ColumnInfo("icon")
    var icon: String? = null

    @ColumnInfo("icon_url")
    var iconUrl: String? = null

    @ColumnInfo("title")
    var title: String? = null
    suspend fun delete(context: Context) {
        try {
            if (!icon.isNullOrEmpty()) {
                val file = File(icon!!)
                file.delete()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        try {
            BrowsRoomHelper.getDao(context).deleteWebFavorite(this)
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }
    companion object {

        // 将 Bitmap 保存到文件
        private fun saveBitmapToFile(context: Context, bitmap: Bitmap?, fileName: String): File? {
            if (bitmap == null) {
                return null
            }

            try {
                // 创建目录
                val directory = File(context.filesDir, "web_favorite")
                if (!directory.exists()) {
                    directory.mkdirs()
                }

                // 创建文件
                val file = File(directory, fileName)
                // 将 Bitmap 写入文件
                val fileOutputStream = FileOutputStream(file)
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)
                fileOutputStream.flush()
                fileOutputStream.close()
                return file
            } catch (e: IOException) {
                e.printStackTrace()
                return null
            }
        }

        suspend fun save(
            context: Context,
            time: Long,
            url: String?,
            icon: Bitmap?,
            title: String?,
            iconUrl: String?
        ): BrowsWebFavoriteBean? {
            if (url.isNullOrEmpty() || !url.startsWith("http")) {
                return null
            }
            return withContext(Dispatchers.IO) {

                try {
                    val bw = BrowsWebFavoriteBean()
                    val dao = BrowsRoomHelper.getDao(context)
                    val savedHistory = dao.getFavoriteByUrl(url)
                    val savedTime = savedHistory?.time?:time
                    val iconFile = if (icon != null) saveBitmapToFile(
                        context,
                        icon,
                        "$time.png"
                    )?.absolutePath else savedHistory?.icon
                    val savedTitle = if (savedHistory?.title.isNullOrEmpty()) title else savedHistory?.title
                    val savedIconUrl =
                        if (iconUrl.isNullOrEmpty()) savedHistory?.iconUrl else iconUrl
                    dao.insert(
                        bw.apply {
                            this.time = savedTime
                            this.webUrl = url
                            this.icon = iconFile
                            this.title = savedTitle
                            this.iconUrl = savedIconUrl
                        })
                    bw
                } catch (e: Exception) {
                    e.printStackTrace()
                    null
                }
            }
        }
    }
}